package com.campus.help.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * Web MVC配置
 * 配置静态资源映射
 *
 * @author campus-help
 * @since 2025-10-25
 */
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private FileStorageConfig fileStorageConfig;

    /**
     * 配置静态资源映射
     * 将 /files/** 映射到本地文件存储路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String uploadPath = fileStorageConfig.getUploadPath();
        
        if (uploadPath != null && !uploadPath.isEmpty()) {
            // 确保路径以文件分隔符结尾
            if (!uploadPath.endsWith(File.separator)) {
                uploadPath += File.separator;
            }
            
            // 转换为file协议URL
            String resourceLocation = "file:" + uploadPath;
            
            // 配置静态资源映射
            // 访问路径：http://localhost:3333/api/files/images/2025/10/25/xxx.jpg
            // 映射到：uploadPath/images/2025/10/25/xxx.jpg
            registry.addResourceHandler("/files/**")
                    .addResourceLocations(resourceLocation)
                    .setCachePeriod(3600 * 24 * 30); // 缓存30天
            
            log.info("静态资源映射配置成功：/files/** -> {}", resourceLocation);
        } else {
            log.warn("文件存储路径未配置，静态资源映射未生效");
        }
    }
}


